// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package mobile_verify

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib/authorizer"
)

// Logic
// 修改手机号.
type Logic struct {
	auth     *authorizer.Authentication
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

// Run
// 处理过程.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err           error
		has           bool
		res           = result.New()
		mobile        *models.UserMobiles
		mobileService = services.NewUserMobilesService()
	)

	// 1. 读取绑定.
	//    使用完整手机号查询用户最近使用的手机号是否正确.
	if mobile, has, err = mobileService.Dao.GetBy(ctx, "mobile", o.request.Mobile.String()); err != nil {
		return res.WithError(errs.ErrDatabaseQuery)
	} else if !has || mobile.UserId != o.auth.UserId {
		return res.WithError(errs.ErrUserMobileNotBind)
	}

	// 2. 校验成功.
	o.response.Mobile = mobile.Mobile.Mask()
	o.response.UserId = o.auth.UserId
	return res.With(o.response)
}
